from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import time
from account.models import User
from article.models import Article
from comment.models import comment


# Create your views here.
@csrf_exempt
@require_POST
@login_required(login_url='/account/login/')
def comment_post(request):
    a_id = request.POST.get('a_id')
    content = request.POST.get('content')
    upload_time = int(request.POST.get('timestamp'))
    try:
        new_comment = comment(u=request.user,
                              p_id=a_id,
                              content=content,
                              upload_time=upload_time)
        new_comment.save()
        return JsonResponse({'msg': 'success'})
    except Exception as e:
        return JsonResponse({'msg': 'error'})


@csrf_exempt
@require_POST
@login_required(login_url='/account/login/')
def comment_show(request):
    a_id = request.POST.get('a_id')
    comment_items = comment.objects.filter(p_id=a_id).values()
    for item in comment_items:
        comment_id = item['id']
        u_id = item['u_id']
        item['AuthorInfo'] = {i: j for i, j in User.objects.filter(pk=u_id).values()[0].items() if
                              i not in ['password', 'date_joined', 'is_active', 'last_login','email']}
        item['Title'] = Article.objects.get(pk=a_id).title
        print(item['upload_time'])
        item['UploadTimeStr'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(item['upload_time']/1000))
        item['UploadTimeStamp'] = item['upload_time']
        item['is_like'] = comment.objects.get(pk=comment_id).like.count()
        item.pop('upload_time')
    return JsonResponse({'data': list(comment_items), 'msg': 'success'})
